package com.bruce.apkinstaller;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;


/**
 * Created by Bruce on 2017/10/18.
 */

public final class Receiver extends BroadcastReceiver {
    private static final String TAG = Receiver.class.getSimpleName();

    /*存储设备状态监听*/
    private static final String ACTION_USB = "android.intent.action.MEDIA_MOUNTED";
    /*开机监听*/
    public static final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED";
    /*桌面应用启动完成监听*/
    public static final String ACTION_LAUNCHER_COMPLETED = "android.intent.action.LAUNCHER_LAUNCH_COMPLETED";
    /*资源更新完成*/
    public static final String ACTION_ASSETS_UPDATE_COMPLETED = "com.htrip.assetsmodule.ASSETS_UPDATE_COMPLETE";
    /*升级应用*/
    public static final String ACTION_APP_UPDATE = "com.htrip.assetsmodule.APP_UPDATE";
    /*要安装的应用列表*/
    public static final String ACTION_APK_LIST = "apkList";
    /*指定安装类型*/
    public static final String ACTION_INSTALL_TYPE = "installType";
    /*指定操作类型，安装还是卸载*/
    public static final String ACTION_OPTION_TYPE = "installOrUninstall";

    private ArrayList<String> apkList = new ArrayList<>();

    @Override
    public void onReceive(final Context context, Intent intent) {
        Log.d(TAG, "receiver broadcast: " + intent.getAction());
        switch (intent.getAction()) {
            case ACTION_USB:
                break;
            case ACTION_BOOT:
                /*开机后启动资源更新任务*/
//                context.startService(new Intent(context, DownloadService.class));
                break;
            case ConnectivityManager.CONNECTIVITY_ACTION:
                break;
            case ACTION_LAUNCHER_COMPLETED:
                 /*如果系统没有开机广播，则通过launcher启动完成后发广播通知所有资源更新*/
                break;

            case ACTION_APP_UPDATE:
                try {
//                    apkList = (ArrayList<String>) DataModel.queryAppList(context);
//                    intent.putStringArrayListExtra(Receiver.ACTION_APK_LIST, apkList);
                    Log.d(TAG, "升级应用： " + intent.getAction() + "\n 数据：" + intent.getStringArrayListExtra(ACTION_APK_LIST).toString());
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setClass(context, InstallService.class);
                    context.startService(intent);
                } catch (Exception e) {
                    Toast.makeText(context, "升级应用错误：" + e.toString(), Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
                break;
        }
    }
}
